<template>
  <a-card :bordered="false" :bodyStyle="bodyStyle">
    <a-spin :spinning="loading">
      <a-tree
        showLine
        v-if="type=='dept'"
        :selectedKeys="selectedKeys"
        :treeData="treeData"
        :load-data="onLoadData"
        :expandedKeys.sync="theExpandedKeys"
        @select="handleTreeSelect"
      >
        <template slot="title" slot-scope="record">
          <span :title="record.title" v-if="orgTreeShowDeptAbbr && record.attributes && record.attributes.nameAbbr">{{record.attributes.nameAbbr}}</span>
          <span :title="record.title" v-else>{{record.title}}</span>
        </template>
      </a-tree>
      <a-tree
        showLine
        v-if="type!='dept'"
        :selectedKeys="selectedKeys"
        :treeData="treeData"
        :expandedKeys.sync="theExpandedKeys"
        @select="handleTreeSelect"
      />
    </a-spin>
  </a-card>
</template>

<script>

  import { getAction } from '@/api/manage'
  import YchConstant from "@/api/YchConstant";
  import config from '@/settings'

  export default {
    name: 'LeftTree',
    props: {
      value: {
        type: String,
        default: null
      },
      treeDataSource: {
        type: Array,
        default: () => []
      },
      expandedKeys:{
        type: Array,
        default: () => []
      },
      type:{
        type:String,
        default:null
      },
      orgTreeShowDeptAbbr:{
        type:Boolean,
        default:config.orgTreeShowDeptAbbr
      },
      height: {
        type: Number,
        default: 300
      },
    },
    data () {
      return {
        theExpandedKeys:this.expandedKeys,
        treeData:this.treeDataSource,
        loading:false,
        url:{
          getSubDeptTreeByDepartIdUrl:YchConstant.PREFIX_BPM + '/bpm-front/displayRest/getSubDeptTreeByDepartId/v1'
        }
      }
    },
    computed: {
      selectedKeys () {
        return this.value ? [this.value] : []
      },
      bodyStyle() {
        return {height: (this.height + 90) + 'px', overflow: 'auto', padding: '0'}
      }
    },
    methods: {
      handleTreeSelect (selectedKeys) {
        this.$emit('input', selectedKeys[0])
      },
      onLoadData(treeNode) {
        return new Promise(resolve => {
          if (treeNode.dataRef.children) {
            resolve();
            return;
          }
          this.loading = true
          getAction(this.url.getSubDeptTreeByDepartIdUrl, {
            departId: treeNode.value
          }).then((res) => {
            if (res.success) {
              treeNode.dataRef.children = res.result;
              this.treeData = [...this.treeData];
              resolve();
            } else {
              this.messageUtil.warning(res.message)
            }
          }).finally(() => {
            this.loading = false
          })
        });
      },
    }
  }
</script>
